package com.lovezy.platform.core.sms.provider;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.lovezy.platform.core.sms.SmsProvider;
import com.lovezy.platform.core.sms.SmsResponse;
import com.lovezy.platform.core.sms.SmsTarget;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * 阿里大鱼服务提供商
 * Created by jin on 2017/11/10.
 */
@ConfigurationProperties(prefix = "app.sms.provider.alidayu")
public class AliDayuSmsProvider extends SmsProvider{

    @Override
    public SmsResponse send(SmsTarget target) {
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", appKey,
                appSecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", serverUrl);
        } catch (ClientException e) {
            log.error("发送阿里大于短信失败", e);
        }

        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
        request.setPhoneNumbers(target.getMobile());
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(getSignName());
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(target.getTemplateCode());
        request.setTemplateParam("{\"code\":\"" + target.getText() + "\"}");

        //请求失败这里会抛ClientException异常
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            log.error("发送短信失败", e);
            return new SmsResponse(false, e.getErrCode() + ":" + e.getErrMsg());
        }
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            return new SmsResponse();
        }else{
            return new SmsResponse(false, sendSmsResponse.getCode() + ":" + sendSmsResponse.getMessage());
        }
    }
}
